package org.ohosannotations.sample;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.data.rdb.RdbStore;
import ohos.event.intentagent.IntentAgent;
import ohos.event.intentagent.IntentAgentConstant;
import ohos.event.intentagent.IntentAgentHelper;
import ohos.event.intentagent.IntentAgentInfo;
import ohos.event.notification.NotificationHelper;
import ohos.event.notification.NotificationRequest;
import ohos.event.notification.NotificationSlot;
import ohos.global.resource.NotExistException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.multimodalinput.event.TouchEvent;
import ohos.rpc.RemoteException;

import org.ohosannotations.annotations.Background;
import org.ohosannotations.annotations.Click;
import org.ohosannotations.annotations.ComponentById;
import org.ohosannotations.annotations.EAbility;
import org.ohosannotations.annotations.LongClick;
import org.ohosannotations.annotations.Touch;
import org.ohosannotations.annotations.Transactional;
import org.ohosannotations.annotations.UiThread;
import org.ohosannotations.annotations.res.BooleanRes;
import org.ohosannotations.annotations.res.ColorRes;
import org.ohosannotations.annotations.res.StringRes;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * 我的能力
 *
 * @author dev
 * @since 2021-07-23
 */
@EAbility(ResourceTable.Layout_my_ability)
public class MyAbility extends Ability implements Component.ClickedListener {
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0x000001, "MyAbility");
    private static final int CONSTANT_20 = 20;
    private static final int TIME = 3000;
    @ComponentById
    TextField myTextField;

    @ComponentById(ResourceTable.Id_myText)
    Text text;

    @StringRes(ResourceTable.String_hello)
    String helloFormat;

    @ColorRes
    int ohosColor;

    @BooleanRes
    boolean someBoolean;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
    }

    @Click
    void myButtonClicked() {
        String name = myTextField.getText().toString();
        someBackgroundWork(name, 5);
    }

    @Override
    protected void onActive() {
        super.onActive();
        myTextField.setClickedListener(this);
    }

    @Background
    void someBackgroundWork(String name, long timeToDoSomeLongComputation) {
        try {
            TimeUnit.SECONDS.sleep(timeToDoSomeLongComputation);
        } catch (InterruptedException error) {
            HiLog.error(TAG, " someBackgroundWork InterruptedException ", error);
        }

        String message = String.format(helloFormat, name);

        updateUi(message, ohosColor);

        showNotificationsDelayed();
    }

    @UiThread
    void updateUi(String message, int color) {
        text.setText(message);
        text.setTextColor(new Color(color));
    }

    // @TargetApi
    @UiThread(delay = 2000)
    void showNotificationsDelayed() {
        List<Intent> intents = new ArrayList<>();
        intents.add(new Intent());
        IntentAgentInfo intentAgentInfo = new IntentAgentInfo(0,
            IntentAgentConstant.OperationType.UNKNOWN_TYPE, IntentAgentConstant.Flags.CONSTANT_FLAG, intents, null);
        IntentAgent contentIntent = IntentAgentHelper.getIntentAgent(this, intentAgentInfo);

        NotificationSlot slot = new NotificationSlot("1", "slot_default", NotificationSlot.LEVEL_MIN);

        try {
            NotificationHelper.addNotificationSlot(slot);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        NotificationRequest request = new NotificationRequest();
        request.setLittleIcon(getPixelMapFromResource(ResourceTable.Media_icon));

        NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
        content.setTitle("My notification");
        content.setText("Hello, World!");
        request.setIntentAgent(contentIntent);

        try {
            NotificationHelper.publishNotification(request);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @LongClick
    void startExtraAbility() {
        Intent intent = AbilityWithExtra_.intent(this).myDate(new Date()).myMessage("hello !").get();
        intent.setParam(AbilityWithExtra.MY_INT_EXTRA, "null");
        startAbility(intent);
    }

    @Click
    void startListAbility(Component v1) {
        Intent intent = new Intent();
        intent.setOperation(new Intent.OperationBuilder()
            .withBundleName(BuildConfig.BUNDLE_NAME)
            .withAbilityName(BuildConfig.BUNDLE_NAME + ".MyListAbility_").build());
        startAbility(intent);
    }

    @Touch
    void myText(TouchEvent event) {
    }

    @Transactional
    int transactionalMethod(RdbStore rs, int someParam) {
        return 42;
    }

    private PixelMap getPixelMapFromResource(int resourceId) {
        InputStream inputStream = null;
        PixelMap pixelMap = null;
        try {
            // 创建图像数据源ImageSource对象
            inputStream = getResourceManager().getResource(resourceId);
            ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
            srcOpts.formatHint = "image/png";
            ImageSource imageSource = ImageSource.create(inputStream, srcOpts);

            // 设置图片参数
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            pixelMap = imageSource.createPixelmap(decodingOptions);
            return pixelMap;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException error) {
                    HiLog.error(TAG," getPixelMapFromResource IOException ",error);
                }
            }
        }
        return pixelMap;
    }

    @Override
    public void onClick(Component component) {
        myTextField.setBubbleSize(AttrHelper.vp2px(CONSTANT_20,
            MyAbility.this), AttrHelper.vp2px(CONSTANT_20, MyAbility.this));
        myTextField.setBubbleElement(new ShapeElement(MyAbility.this, ResourceTable.Graphic_text_field_bubble));
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                myTextField.setBubbleElement(new ShapeElement());
                timer.cancel();
            }
        }, TIME);
    }
}
